package com.crawler.clent;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.common.collect.Lists;

public class ClientTest {

	private CloseableHttpClient client;
	

	public CloseableHttpClient getClient() {

		
		SSLContext sslcontext = null;
		try {
			sslcontext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
			    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			        return true;
			    }
			}).build();
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();
		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
				.<ConnectionSocketFactory> create()
				.register("http", PlainConnectionSocketFactory.INSTANCE)
				.register("https",new SSLConnectionSocketFactory(sslcontext,hostnameVerifier)).build();

		PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		connManager.setMaxTotal(1100); 
        connManager.setDefaultMaxPerRoute(100);
        
        CookieStore cookieStore = new BasicCookieStore();
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                							.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
//	                						.setCookieSpec(CookieSpecs.BEST_MATCH)
							                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
							                .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
							                .build();
        
		client = HttpClients.custom()
	            .setConnectionManager(connManager)
	            .setDefaultCookieStore(cookieStore)
	            .setDefaultCredentialsProvider(credentialsProvider)
	            .setDefaultRequestConfig(defaultRequestConfig).build();
		
		
		RequestConfig.copy(defaultRequestConfig)
                	 .setSocketTimeout(60000)
                	 .setConnectTimeout(10000)
                	 .setConnectionRequestTimeout(5000)
                	 .build();
	
		return client;
	}

	public void setClient(CloseableHttpClient client) {
		this.client = client;
	}
	
	/**
	 * 登陆测试
	 */
	public static void main(String[] args) throws Exception {
		
		ClientTest client = new ClientTest();
		CloseableHttpClient httpClient = client.getClient();
		
		HttpGet get = new HttpGet("https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn");
		CloseableHttpResponse resp = httpClient.execute(get);
		String content = EntityUtils.toString(resp.getEntity(),"gb2312");
		Document doc = Jsoup.parse(content);
		doc.select("input");
		String lt = doc.getElementsByAttributeValue("name", "lt").get(0).attr("value");
		String execution = doc.getElementsByAttributeValue("name", "execution").get(0).attr("value");
		
		List<NameValuePair> params = Lists.newArrayList();
		params.add(new BasicNameValuePair("username", "xiaoqiu136@126.com"));
		params.add(new BasicNameValuePair("password", "123123"));
		params.add(new BasicNameValuePair("_eventId", "submit"));
		params.add(new BasicNameValuePair("execution", execution));
		params.add(new BasicNameValuePair("lt", lt));
		HttpEntity httpEntity = new UrlEncodedFormEntity(params);
		
		String url = "http://passport.csdn.net/account/login?from=http%3A%2F%2Fmy.csdn.net%2Fmy%2Fmycsdn";
		HttpPost httpPost = new HttpPost(url);
		List<Header> headers = Lists.newArrayList();
		headers.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
		headers.add(new BasicHeader("Accept-Encoding", "gzip, deflate"));
		headers.add(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"));
		headers.add(new BasicHeader("Connection", "keep-alive"));
		headers.add(new BasicHeader("Host", "passport.csdn.net"));
		httpPost.setHeaders(headers.toArray(new Header[0]));
		httpPost.setEntity(httpEntity);
		
		CloseableHttpResponse response = httpClient.execute(httpPost);
		content = EntityUtils.toString(response.getEntity(),"gb2312");
		System.out.println(content);
		
	}
}
